package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LineChart linechart = findViewById(R.id.lineChart);
        float[] f1 = {1.0f, 9.0f, 3.0f, 4.0f, 7.0f, 3.0f, 5.0f, 1.0f, 7.0f};
        float[] f2 = {2.0f, 1.0f, 4.0f, 1.0f, 5.0f, 9.0f, 2.0f, 6.0f, 5.0f};

        List<ILineDataSet> s = new ArrayList<>();
        LineDataSet demo1 = (getDataSet(f1, "demo1"));//一个LineDataSet就是一条线
        demo1.setColor(Color.parseColor("#ff0000"));//线颜色
        demo1.setLineWidth(1.6f);//线宽度
        demo1.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);//线条平滑
        s.add(demo1);

        LineDataSet demo2 = (getDataSet(f2, "demo2"));
        demo2.setColor(Color.parseColor("#00ff00"));
        demo2.setLineWidth(3.2f);
        demo2.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        s.add(demo2);

        XAxis xAxis = linechart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawAxisLine(true);

        YAxis yAxis = linechart.getAxisLeft();//得到Y轴
        YAxis rightYAxis = linechart.getAxisRight();
        rightYAxis.setEnabled(false);
        yAxis.setGranularity(1);

        Legend legend = linechart.getLegend();
        legend.setEnabled(false);

        linechart.setData(new LineData(s));
        linechart.invalidate();
    }

    private LineDataSet getDataSet(float[] f, String title) {
        //设置数据
        List<Entry> data = new ArrayList<>();
        for (int x = 0; x < f.length; x++) {
            Entry entry = new Entry(x, f[x]);
            data.add(entry);
        }
        return new LineDataSet(data, title);
    }
}